package com.keepers.repair.fragment

import android.os.Bundle
import android.preference.Preference
import android.preference.PreferenceFragment
import android.support.design.widget.TextInputEditText
import android.text.Editable
import android.text.InputType.TYPE_CLASS_TEXT
import android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD
import android.text.TextWatcher
import android.util.Log
import android.view.Gravity.CENTER
import com.keepers.repair.R
import com.keepers.repair.model.ServerModel
import com.keepers.repair.utils.*
import org.jetbrains.anko.*
import org.jetbrains.anko.design.textInputEditText
import org.jetbrains.anko.design.textInputLayout

class SettingsFragment : PreferenceFragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        addPreferencesFromResource(R.xml.settings)
        configUserInfo()
        configServerInfo()
        configOtherInfo()
    }

    private fun configUserInfo() {
        val user = getUser(this.activity) ?: return
        val accountSetting = findPreference(getString(R.string.settings_key_account))
        val nameSetting = findPreference(getString(R.string.settings_key_name))
        val groupSetting = findPreference(getString(R.string.settings_key_group))
        val roleSetting = findPreference(getString(R.string.settings_key_role))
        val passwordSetting = findPreference(getString(R.string.settings_key_password))
        val logoutSetting = findPreference(getString(R.string.settings_key_logout))

        accountSetting.isEnabled = true
        nameSetting.isEnabled = true
        groupSetting.isEnabled = true
        roleSetting.isEnabled = true
        passwordSetting.isEnabled = true
        logoutSetting.isEnabled = true

        accountSetting.summary = user.UserName
        nameSetting.summary = user.Name
        groupSetting.summary = user.GroupName
        roleSetting.summary = user.RoleName
        passwordSetting.setOnPreferenceClickListener { _ ->
            alert {
                var oldEditor: TextInputEditText? = null
                var newEditor: TextInputEditText? = null
                var repEditor: TextInputEditText? = null
                title = "修改密码"
                this.customView {
                    verticalLayout {
                        padding = 50
                        textInputLayout {
                            isPasswordVisibilityToggleEnabled = true
                            oldEditor = textInputEditText {
                                hint = "原始密码"
                                inputType = TYPE_CLASS_TEXT or TYPE_TEXT_VARIATION_PASSWORD
                            }
                        }
                        textInputLayout {
                            isPasswordVisibilityToggleEnabled = true
                            newEditor = textInputEditText {
                                hint = "新密码"
                                inputType = TYPE_CLASS_TEXT or TYPE_TEXT_VARIATION_PASSWORD
                            }
                        }
                        textInputLayout {
                            repEditor = textInputEditText {
                                hint = "重复密码"
                                inputType = TYPE_CLASS_TEXT or TYPE_TEXT_VARIATION_PASSWORD
                            }
                            repEditor?.addTextChangedListener(object : TextWatcher {
                                override fun afterTextChanged(p0: Editable?) {}
                                override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
                                override fun onTextChanged(charSequence: CharSequence?, p1: Int, p2: Int, p3: Int) {
                                    val str = charSequence.toString()
                                    if (str != newEditor?.text?.toString()) {
                                        repEditor?.error = "输入重复密码错误"
                                    } else {
                                        repEditor?.error = null
                                    }
                                }
                            })
                        }
                    }
                }
                noButton {}
                yesButton { _ ->
                    if (oldEditor?.text?.isEmpty() == true || newEditor?.text?.isEmpty() == true || repEditor?.text?.isEmpty() == true) {
                        alert("表单没有完成", "错误") { yesButton {} }.show()
                        return@yesButton
                    }
                    if (newEditor?.text?.toString()?.equals(repEditor?.text?.toString()) != true) {
                        alert("密码重复错误，请重试", "错误") { yesButton {} }.show()
                        return@yesButton
                    }
                    Log.d("Hell", "balabala")
                }
            }.show()
            true
        }
        logoutSetting.setOnPreferenceClickListener { _ ->
            val activity = this.activity
            alert("确定要退出登录么？") {
                noButton {}
                yesButton {
                    if (getUser(activity) != null) {
                        setUser(activity, null)
                        activity.finish()
                    }
                }
            }.show()
            true
        }
    }

    private fun configServerInfo() {
        val hostSetting = findPreference(getString(R.string.settings_key_server_host))
        val portSetting = findPreference(getString(R.string.settings_key_server_port))
        val checkSetting = findPreference(getString(R.string.setting_key_server_check))
        val defaultSetting = findPreference(getString(R.string.settings_key_server_default))
        hostSetting.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, value ->
            val url = ServerModel(activity.server.host, value as Int).url
            Api.setBaseUrl(url)
            true
        }
        portSetting.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, value ->
            val url = ServerModel(value as String, activity.server.port).url
            Api.setBaseUrl(url)
            true
        }
        checkSetting.setOnPreferenceClickListener { _ ->
            val progress = indeterminateProgressDialog(title = "正在检查") {
                Api.hello({ _ ->
                    this.dismiss()
                    alert("测试成功") { yesButton {} }.show()
                }, { _ ->
                    this.dismiss()
                    alert("测试失败") { yesButton {} }.show()
                })
            }
            progress.show()
            true
        }
        defaultSetting.setOnPreferenceClickListener { _ ->
            val context = this
            alert("将要还原服务器默认设置？") {
                noButton {}
                yesButton {
                    val sharedPreferences = context.defaultSharedPreferences
                    val edit = sharedPreferences.edit()
                    edit.putString(getString(R.string.settings_key_server_host), Config.httpHost)
                    edit.putString(getString(R.string.settings_key_server_port), Config.httpPort.toString())
                    edit.apply()
                    Api.setBaseUrl(Config.httpUrl)
                }
            }.show()
            true
        }
    }

    private fun configOtherInfo() {
        val versionSettings = findPreference(getString(R.string.settings_key_version))
        val aboutSettings = findPreference(getString(R.string.settings_key_about))

        versionSettings.summary = "当前版本 - ${getVersion(activity)}"
        aboutSettings.setOnPreferenceClickListener { _ ->
            alert(getString(R.string.app_name)) {
                customView {
                    frameLayout {
                        imageView {
                            if (getIcon(activity) != null) backgroundResource = getIcon(activity)!!
                        }.lparams(width = 500, height = 500, gravity = CENTER)
                    }
                }
                yesButton {}
            }.show()
            true
        }
    }
}
